// script.js

const dropzone = document.getElementById('dropzone');
const fileInput = document.getElementById('file-input');
const message = document.getElementById('message');

window.addEventListener('DOMContentLoaded', () => {
    // 页面加载时恢复
    const savedDeviceName = getLocalStorageWithExpiry('deviceName');
    if (savedDeviceName) {
        document.getElementById('deviceName').value = savedDeviceName;
    }
});

// 当文件拖到 dropzone 上方时触发
dropzone.addEventListener('dragover', (e) => {
    e.preventDefault(); // 必须！阻止浏览器默认行为（否则会打开文件）
    dropzone.classList.add('dragover'); // 加上高亮样式（边框变蓝、背景变浅）
});

// 当文件离开 dropzone 区域时触发
dropzone.addEventListener('dragleave', () => {
    dropzone.classList.remove('dragover');
});

// 当用户在 dropzone 里松开鼠标（真正放下文件）时触发
dropzone.addEventListener('drop', (e) => {
    e.preventDefault(); // 同样阻止浏览器把文件打开
    dropzone.classList.remove('dragover'); // 去掉高亮
    uploadFiles(e.dataTransfer.files); // 把文件列表传给上传函数
});

fileInput.addEventListener('change', () => {
    uploadFiles(fileInput.files);
});

function uploadFiles(files) {
    console.log('上传文件数量:', files.length);
    document.querySelectorAll('.new-upload').forEach(el => el.remove());
    const pc = document.getElementById('progress-container');
    const bar = document.getElementById('progress-bar');
    const txt = document.getElementById('progress-text');

    pc.style.display = 'block'; // 这里显示
    bar.style.width = '0%';
    txt.textContent = '0%';

    const formData = new FormData();
    for (let i = 0; i < files.length; i++) formData.append('file', files[i]);

    const deviceName = document.getElementById('deviceName').value.trim();
    setLocalStorageWithExpiry('deviceName', deviceName, 90 * 24 * 60);
    if (deviceName) {
        formData.append('device_name', deviceName);
    }

    const xhr = new XMLHttpRequest();
    xhr.open('POST', './uploadFiles');

    let lastLoaded = 0;
    let lastTime = Date.now();

    xhr.upload.addEventListener('progress', e => {
        if (!e.lengthComputable) return;

        const percent = Math.round((e.loaded / e.total) * 100);
        const now = Date.now();
        const deltaTime = (now - lastTime) / 1000;
        const deltaLoaded = e.loaded - lastLoaded;

        let speed = 0;
        let eta   = '--:--';

        if (deltaTime > 0) {
            speed = deltaLoaded / deltaTime;          // 字节/秒

            const remainBytes = e.total - e.loaded;
            const remainSec   = remainBytes / speed;
            const m = Math.floor(remainSec / 60);
            const s = Math.floor(remainSec % 60);
            eta = `${m.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`;
        }

        bar.style.width = percent + '%';
        txt.textContent = `${percent}% | ${
            speed < 1024 * 1024
                ? (speed / 1024).toFixed(1) + ' KB/s'
                : (speed / 1024 / 1024).toFixed(1) + ' MB/s'
        } | ${eta}`;

        lastLoaded = e.loaded;
        lastTime = now;
    });

    xhr.addEventListener('load', () => {
        pc.style.display = 'none';
        console.log("status =",  xhr.status)
        if (xhr.status === 200) {
            const data = JSON.parse(xhr.responseText);
            data.results.forEach(res => {
                const div = document.createElement('div');
                div.className = res.includes('上传成功') ? 'new-upload success' : 'new-upload failure';
                div.innerHTML = res;
                message.appendChild(div);
            });
        } else {
            const div = document.createElement('div');
            div.className = 'new-upload failure';
            div.innerHTML = '上传失败：服务器错误';
            message.appendChild(div);
        }
        fileInput.value = '';
    });

    xhr.addEventListener('error', () => {
        console.log('XHR 状态:', xhr.status);
        console.log('XHR 响应体:', xhr.responseText);

        pc.style.display = 'none';
        const div = document.createElement('div');
        div.className = 'new-upload failure';
        div.innerHTML = '上传失败：网络错误。目前仅支持拖拽文件，而非文件夹';
        message.appendChild(div);
    });

    console.log('FormData 内容:', formData);
    xhr.send(formData);
}

function setLocalStorageWithExpiry(key, value, ttlMinutes) {
    const now = new Date().getTime();
    const item = {
        value: value,
        expiry: now + ttlMinutes * 60 * 1000
    };
    localStorage.setItem(key, JSON.stringify(item));
}

function getLocalStorageWithExpiry(key) {
    const itemStr = localStorage.getItem(key);
    if (!itemStr) return null;

    const item = JSON.parse(itemStr);
    const now = new Date().getTime();

    if (now > item.expiry) {
        localStorage.removeItem(key);
        return null;
    }
    return item.value;
}

// 仅在悬停时显示，离开时隐藏
function toggleDropdown() {
    const menu = document.getElementById('dropdown-menu');
    const btnContainer = document.querySelector('.file-btn-container');

    // 只是显示或隐藏，需根据当前状态 判断
    if (menu.classList.contains('show')) {
        // 如果当前显示，且鼠标不在按钮容器内，则隐藏
        if (!btnContainer.contains(document.activeElement)) {
            menu.classList.remove('show');
        }
    } else {
        // 如果当前隐藏，则显示
        menu.classList.add('show');
    }
}

function selectFiles() {
    const input = document.getElementById('file-input');
    input.removeAttribute('webkitdirectory'); // 清除文件夹模式
    input.click(); // 触发文件选择器
    toggleDropdown(); // 关闭下拉菜单
}

function selectFolder() {
    // 浏览器不支持直接选择文件夹，但可通过 webkitdirectory 属性实现
    const input = document.getElementById('file-input');
    input.setAttribute('webkitdirectory', 'true');
    input.click();
    toggleDropdown();
}

function showDropdown() {
    const menu = document.getElementById('dropdown-menu');
    menu.classList.add('show');
}

function hideDropdown() {
    const menu = document.getElementById('dropdown-menu');
    const btnContainer = document.querySelector('.file-btn-container');
    const dropdownMenu = document.getElementById('dropdown-menu');

    // 获取鼠标当前位置
    const x = event.clientX;
    const y = event.clientY;

    // 判断鼠标是否仍在 button容器或下拉菜单区域内
    const element = document.elementFromPoint(x, y);
    const isInsideBtnContainer = btnContainer.contains(element);
    const isInsideDropdownMenu = dropdownMenu.contains(element);

    // 如果不在任一区域内，则隐藏菜单
    if (!isInsideBtnContainer && !isInsideDropdownMenu) {
        menu.classList.remove('show');
    }
}

window.addEventListener('click', (e) => {
    const menu = document.getElementById('dropdown-menu');
    const btnContainer = document.querySelector('.file-btn-container');

    // 如果点击的是按钮容器外且菜单已打开，则关闭
    if (!btnContainer.contains(e.target) && menu.classList.contains('show')) {
        menu.classList.remove('show');
    }
});
